<?php

namespace App\Models;

use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

/*资源外部类型-所以资源商合在一起的资源类型model*/

class ResourceTypeExternal extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';


    protected $table = 'resource_type_external';

    /**
     * 获取筛选列表
     */
    public function getFilterLists($resource_business_id, $big_type_id)
    {
        $res = $this->select('id', 'type_name')->where(function ($query) use ($resource_business_id, $big_type_id) {
            if ($resource_business_id) {
                $resource_business_id = !is_array($resource_business_id) ? explode(',', $resource_business_id) : $resource_business_id;
                $query->whereIn('resource_business_id', $resource_business_id);
            }
            if ($big_type_id) {
                $big_type_id = !is_array($big_type_id) ? explode(',', $big_type_id) : $big_type_id;
                $query->whereIn('big_type_id', $big_type_id);
            }
        })
            ->where('is_del', 1)
            ->where('number', '>', 0)
            ->orderByDesc('id')
            ->get()
            ->toArray();
        return $res;
    }


    /**
     * 检索 mysql 数据 （全数据检索）
     * @param keywords 检索条件
     * @param resource_business_id 资源商id
     * @param is_exclude_empty 是否排除空的数据 1 排除，其余不排除
     * @param big_type_id 类型id
     * @param limit int 分页大小
     */
    public function getResourceTypeList($resource_business_id = null, $big_type_id = null, $keywords, $is_exclude_empty = null, $limit = 10)
    {

        $manage_resource_business_ids = !empty($this->request->manage_info['resource_business_ids']) ? $this->request->manage_info['resource_business_ids'] : [];

        $type_id_all  = [];
        if ($is_exclude_empty == 1) {
            $type_id_all = ResourceTotal::where('is_del', 1)->groupBy('type_id')->orderByDesc('id')->pluck('type_id')->toArray();
        }

        $res = $this->select('id', 'type_name', 'img', 'create_time', 'number as resource_num')
            ->where(function ($query) use ($keywords) {
                if ($keywords) {
                    $query->where('type_name', 'like', "%$keywords%");
                }
            })->where(function ($query) use ($resource_business_id, $big_type_id) {
                if ($resource_business_id) {
                    $query->where('resource_business_id', $resource_business_id);
                }
                if ($big_type_id) {
                    $query->where('big_type_id', $big_type_id);
                }
            })->where(function ($query) use ($is_exclude_empty, $type_id_all) {
                if ($is_exclude_empty == 1) {
                    $query->whereIn('id', $type_id_all);
                }
            })->where(function ($query) use ($manage_resource_business_ids) {
                if ($manage_resource_business_ids) {
                    $manage_resource_business_ids = is_array($manage_resource_business_ids) ? $manage_resource_business_ids : explode(',', $manage_resource_business_ids);
                    $query->whereIn('resource_business_id', $manage_resource_business_ids);
                }
            })
            ->where('is_del', 1)
            ->groupBy('type_name')
            ->orderByDesc('number')
            //  ->orderBy('letter')
            ->orderByDesc('id')
            ->paginate($limit)
            ->toArray();

        return $res;
    }


    /**
     * 获取类型名称，没有则添加资源
     **/
    public function getTypeNameNoAdd($data)
    {
        $obj = new self();
        if (in_array($data['resource_business_id'], [3, 4, 6]) && !empty($data['class_type_id'])) {
            $type = $obj->where('resource_business_id', $data['resource_business_id'])->where('class_type_id', $data['class_type_id'])->first();
        } else {
            $type = $obj->where('resource_business_id', $data['resource_business_id'])->where('type_name', $data['name'])->first();
        }
        if ($type) {
            $type->letter = get_first_charter($data['name']); //获取名称首字母
            $type->is_del = 1; //可能是删除的数据，现在恢复
            $type->save();
            return $type->id;
        } else {
            $obj->type_name = $data['name'];
            $obj->level = $data['level'] ?? null;
            $obj->resource_business_id = $data['resource_business_id'];
            $obj->big_type_id = $data['big_type_id'];
            $obj->parent_id = $data['parent_id'] ?? null;
            $obj->parent_name = $data['parent_name'] ?? null;
            $obj->class_type_id = $data['class_type_id'] ?? null;
            $obj->original_id = $data['original_id'] ?? null;
            $obj->letter = get_first_charter($data['name']); //获取名称首字母
            $obj->save();
            return $obj->id;
        }
    }

    /**
     * 根据类型原始id，获取现有id
     * @param resource_business_id 资源商id  只有2才能获取数据
     * @param original_id 原始id
     */
    public function getQqrdTypeIdByOriginalId($resource_business_id, $original_id)
    {
        if ($resource_business_id != 2) {
            return false;
        }
        return $this->where('original_id', $original_id)->where('is_del', 1)->value('id');
    }

    /**
     * 根据类型id，获取是否有相同类型名的类型
     * @param type_id 资源类型id
     */
    public function getTypeNameAllByTypeId($type_id)
    {
        $type_name = $this->where('id', $type_id)->where('is_del', 1)->value('type_name');
        $type_id = $this->where('type_name', $type_name)->where('is_del', 1)->where('number', '>', 0)->pluck('id')->toArray();
        return $type_id;
    }

    /**
     * 重置所有小类型的数量
     */
    public function resetResourceTypeNumber()
    {
        $res = $this->select('id')->where('is_del', 1)->get()->toArray();
        $resourceTotalModel = new ResourceTotal();
        foreach ($res as $val) {
            $number = $resourceTotalModel->getResourceNum(null, null, $val['id']);
            $this->where('id', $val['id'])->update(['number' => $number]);
        }
    }

    /**
     *获取资源商类型名称
     */
    public function getBusinessTypeName($resource_business_id, $resource_business_type_id)
    {
        $resource_business_type_id = is_array($resource_business_type_id) ? $resource_business_type_id : explode(',', $resource_business_type_id);
        $resource_business_type_name = $this->where('resource_business_id', $resource_business_id)->whereIn('id', $resource_business_type_id)->where('is_del', 1)->pluck('type_name')->toArray();
        return $resource_business_type_name ? join(',', $resource_business_type_name) : null;
    }
}
